package com.happy_hao.msg.task;

import com.happy_hao.msg.po.Sender;
import com.happy_hao.msg.util.EmailUtil;
import com.happy_hao.msg.util.SenderUtil;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Component
@Data
//非周期性发送
public class EmailTask implements Runnable {

    private  String taskId;
    private  String fromEmail;
    private  String toEmail;
    private  String subject;
    private  String content;
    private  Queue<Long> intervals; // 存放间隔天数（转换为毫秒）
    private  ScheduledExecutorService executor;
//    private  JavaMailSender mailSender;
    private ScheduledFuture<?> scheduledFuture;

    @Resource
    private SenderUtil senderUtil;

//    public EmailTask(String taskId,String fromEmail, String toEmail, String subject, String content, Queue<Long> intervals,
//                     ScheduledExecutorService executor, JavaMailSender mailSender) {
//        this.fromEmail = fromEmail;
//        this.taskId = taskId;
//        this.toEmail = toEmail;
//        this.subject = subject;
//        this.content = content;
//        this.intervals = intervals;
//        this.executor = executor;
//        this.mailSender = mailSender;
//    }
//    public EmailTask(){}



    @Override
    public void run() {
        // 发送邮件
        sendEmail();

        // 如果还有下一个间隔，则调度下一次任务
        if (!intervals.isEmpty()) {
            System.out.println("111111111");
            long nextInterval = intervals.poll(); // 取出下一个间隔（单位：毫秒）
            scheduledFuture = executor.schedule(this, nextInterval, TimeUnit.MILLISECONDS);
        } else {
            // 如果队列空了，说明已经到达最后阶段（每天一次），所以使用固定间隔（1天）周期性执行
//            scheduledFuture = executor.scheduleAtFixedRate(this, TimeUnit.DAYS.toMillis(1), TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
//            scheduledFuture = executor.scheduleAtFixedRate(this, TimeUnit.SECONDS.toMillis(5), TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
        }
    }

    private void sendEmail() {
            Sender sender = senderUtil.getSender(fromEmail);
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setDefaultEncoding("utf-8");
            javaMailSender.setHost(sender.getHost());
            javaMailSender.setPort(465);
            javaMailSender.setUsername(sender.getUsername());
            javaMailSender.setPassword(sender.getPassword());
            javaMailSender.setProtocol("smtps");
            Properties properties = new Properties();
            properties.put("mail.smtp.connectiontimeout", 5000);
            properties.put("mail.smtp.timeout", 3000);
            properties.put("mail.smtp.writetimeout", "5000");
            properties.put("mail.smtp.auth", true);
            properties.put("mail.smtp.starttls.enable", true);
            properties.put("mail.smtp.starttls.required", true);
            javaMailSender.setJavaMailProperties(properties);
            try{
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();//创建一个邮件消息
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);
                message.setFrom(fromEmail,"msg项目");
                message.setTo(toEmail);
                message.setSubject(subject);
                message.setText(content,true);
                javaMailSender.send(mimeMessage);
            }catch (Exception e){
                e.printStackTrace();
            }
    }

    public void cancel() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
        }
    }
}

